package server

import (
	"context"
	"fmt"
	"gitee.com/go-mid/booter/bootservice"
	"gitee.com/go-mid/infra/xconfig"
	"gitee.com/go-mid/infra/xnet"
	"strings"
	"sync"
)

type ServerStatus string

const (
	ON  ServerStatus = "on"
	OFF ServerStatus = "off"
)

type BaseServer struct {
	sname                  string
	servIp                 string
	copyName               string
	sessKey                string
	servId                 int
	status                 ServerStatus
	muLocks                sync.Mutex
	servInfos              map[string]*bootservice.ServInfo
	services               map[string]bootservice.Service
	preServiceDriverFuncs  []func(ctx context.Context, server Server) error
	postServiceDriverFuncs []func(ctx context.Context, server Server) error
	configCenter           xconfig.ConfigCenter
}

func (m *BaseServer) ServName(ctx context.Context) string {
	m.muLocks.Lock()
	defer m.muLocks.Unlock()
	return m.sname
}

func (m *BaseServer) ServLocation(ctx context.Context) string {
	m.muLocks.Lock()
	defer m.muLocks.Unlock()
	return fmt.Sprintf("%s", m.sname)
}

func (m *BaseServer) ServIp(ctx context.Context) string {
	m.muLocks.Lock()
	defer m.muLocks.Unlock()
	return m.servIp
}

func (m *BaseServer) Servid(ctx context.Context) int {
	m.muLocks.Lock()
	defer m.muLocks.Unlock()
	return m.servId
}

func (m *BaseServer) Copyname(ctx context.Context) string {
	m.muLocks.Lock()
	defer m.muLocks.Unlock()
	return fmt.Sprintf("%s%d", m.sname, m.servId)
}

// RegInfos ...
func (m *BaseServer) ServInfos(ctx context.Context) map[string]*bootservice.ServInfo {
	m.muLocks.Lock()
	defer m.muLocks.Unlock()

	return m.servInfos
}

func (m *BaseServer) setIp() error {
	addr, err := xnet.GetListenAddr("")
	if err != nil {
		return err
	}
	fields := strings.Split(addr, ":")
	if len(fields) < 1 {
		return fmt.Errorf("get listen addr error")
	}
	m.servIp = fields[0]
	return nil
}

func (m *BaseServer) IsStopped(ctx context.Context) bool {
	m.muLocks.Lock()
	defer m.muLocks.Unlock()
	return m.status == OFF
}
func (m *BaseServer) ConfigCenter(ctx context.Context) xconfig.ConfigCenter {
	m.muLocks.Lock()
	defer m.muLocks.Unlock()
	return m.configCenter
}
